// by Xeno
#define THIS_FILE "x_setupserver.sqf"
#include "x_setup.sqf"
if (!isServer) exitWith {};

_pos = [0,0,0];

#ifndef __TT__
if (GVAR(EnableBaseSafeZone) == 0) then {
	// very secret extra thingie...,
	_shield = GVAR(ProtectionZone_inv) createVehicleLocal (position GVAR(FLAG_BASE));
	_shield setDir -211;
	_shield setPos (position GVAR(FLAG_BASE));
	_shield setObjectTexture [0,"#(argb,8,8,3)color(0,0,0,0,ca)"];
	_trig = createTrigger["EmptyDetector" ,position GVAR(FLAG_BASE)];
	_trig setTriggerArea [25, 25, 0, false];
	_trig setTriggerActivation [GVAR(enemy_side_trigger), "PRESENT", true];
	_trig setTriggerStatements ["this", "thislist call {{_x setDamage 1} forEach _this}", ""];
};
#endif

_confmapsize = getNumber(configFile/"CfgWorlds"/worldName/"mapSize");
if (_confmapsize <= 0) then {
	_mpos = markerPos QGVAR(island_marker);
	_mpos set [2,0];
	if (str(_mpos) != "[0,0,0]") then {
		_msize = markerSize QGVAR(island_marker);
		GVAR(island_center) = [_msize select 0, _msize select 1, 300];
		GVAR(island_x_max) = _msize select 0;
		GVAR(island_y_max) = _msize select 1;
	};
} else {
	GVAR(island_center) = [_confmapsize / 2, _confmapsize / 2, 300];
	GVAR(island_x_max) = _confmapsize;
	GVAR(island_y_max) = _confmapsize;
};
GVAR(last_bonus_vec) = "";

[_pos, [0, 0, 0, false], ["NONE", "PRESENT", true], [QGVAR(sm_resolved), "call d_fnc_SideMissionResolved", ""]] call FUNC(CreateTrigger);

#ifdef __TT__
execfsm "fsms\TTPoints.fsm";
#endif

if (GVAR(with_ai)) then {execVM "x_server\x_delaiserv.sqf"};

if (GVAR(MissionType) in [0,2]) then {
	0 spawn {
		scriptName "spawn_x_serversetup_startsm";
		private ["_waittime","_num_p"];
		sleep 20;
		if (GVAR(MissionType) != 2) then {
			_waittime = 200 + random 10;
			_num_p = call FUNC(PlayersNumber);
			if (_num_p > 0) then {
				{
					if (_num_p <= (_x select 0)) exitWith {
						_waittime = (_x select 1) + random 10;
					}
				} forEach GVAR(time_until_next_sidemission);
			};
			sleep _waittime;
		} else {
			sleep 15;
		};
		0 spawn FUNC(getsidemission);
	};
};

#ifndef __TT__
GVAR(air_bonus_vecs) = 0;
GVAR(land_bonus_vecs) = 0;

{
	_vecclass = getText(configFile/"CfgVehicles"/_x/"vehicleClass");
	if (_vecclass == "Air") then {
		__INC(GVAR(air_bonus_vecs));
	} else {
		__INC(GVAR(land_bonus_vecs));
	};
} foreach GVAR(sm_bonus_vehicle_array);
__TRACE_2("","d_air_bonus_vecs","d_land_bonus_vecs");

[GVAR(base_array) select 0, [GVAR(base_array) select 1, GVAR(base_array) select 2, GVAR(base_array) select 3, true], [GVAR(enemy_side_trigger), "PRESENT", true], ["'Man' countType thislist > 0 || {'Tank' countType thislist > 0} || {'Car' countType thislist > 0}", "d_kb_logic1 kbTell [d_kb_logic2,d_kb_topic_side,'BaseUnderAtack','SIDE']", ""]] call FUNC(CreateTrigger);
#endif

if (GVAR(MissionType) == 2) then {
	0 spawn {
		scriptName "spawn_x_serversetup_smonly_endwait";
		waitUntil {sleep 0.344;__XJIPGetVar(all_sm_res)};
		sleep 10;
		[QGVAR(the_end),true] call FUNC(NetSetJIP);
		0 spawn FUNC(DomEnd);
	};
};

// TODO Video wall missing...
/*
0 spawn {
	scriptName "spawn_x_serversetup_pip";
	private ["_unit"];
	sleep 10;
	while {true} do {
		_unit = objNull;
		while {isNull _unit} do {
			_units = if (isMultiplayer) then {playableUnits} else {switchableUnits};
			_unit = _units select (floor (random (count _units)));
			if (isNil "_unit") then {_unit = objNull};
			sleep 0.522;
		};
		[QGVAR(CurPIPVideoTarget), _unit] call FUNC(NetSetJIP);
		[QGVAR(setVideoPIPTar)] call FUNC(NetCallEvent);
		sleep 45 + random 15;
	};
};*/

0 spawn {
	scriptName "spawn_x_serversetup_clean_weaponholder";
	private ["_ct", "_allmisobjs"];
	while {true} do {
		sleep (500 + random 30);
		_allmisobjs = allMissionObjects "groundWeaponHolder";
		sleep 1;
		_helperx = allMissionObjects "WeaponHolder";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "WeaponHolderSimulated";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "WeaponHolder_Single_F";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "Chemlight_green";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "Chemlight_red";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "Chemlight_yellow";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		sleep 1;
		_helperx = allMissionObjects "Chemlight_blue";
		if (count _helperx > 0) then {
			_allmisobjs = [_allmisobjs, _helperx] call FUNC(arraypushstack2);
		};
		{
			if (!isNull _x && {!(_x getVariable [QGVAR(ignore_gc), false])}) then {
				_ct = _x getVariable [QGVAR(checktime), -1];
				if (_ct == -1) then {
					_x setVariable [QGVAR(checktime), time];
				} else {
					if (({isPlayer _x} count ((getPosATL _x) nearEntities ["CAManBase", 100])) == 0) then {
						deleteVehicle _x;
					};
				};
			};
			sleep 0.1;
		} forEach _allmisobjs;
		
		_allmisobjs = allMissionObjects "B_UAV_01_F"; // Small drones
		{
			if (!isNull _x) then {
				_ct = _x getVariable [QGVAR(checktime), -1];
				if (_ct == -1) then {
					_x setVariable [QGVAR(checktime), time];
				} else {
					if ((!isUavConnected _x) || (!canMove _x) || (!alive _x)) then {
						deleteVehicle _x;
					};
				};
			};
			sleep 0.1;
		} forEach _allmisobjs;
		
		_allmisobjs = nil;
	};
};

if (isSteamMission) exitWith {endMission "LOSER"};

0 spawn {
	scriptName "spawn_x_serversetup_clean_crater";
	private "_craters";
	while {true} do {
		sleep (60 + random 60);
		_craters = allMissionObjects "CraterLong" + allMissionObjects "CraterLong_small";
		{
			deleteVehicle _x;
			sleep 0.212;
		} forEach _craters;
		_craters = nil;
	};
};

if (isMultiplayer) then {
	0 spawn {
		scriptName "spawn_x_serversetup_clean_weaponholder_base_box";
		private "_nobs";
		sleep 20;
		while {true} do {
			_nobs = nearestObjects  [GVAR(le_player_boxbos), ["GroundWeaponHolder"], 10];
			if (count _nobs > 0) then {
				{
					if (({isPlayer _x} count ((getPosATL _x) nearEntities ["CAManBase", 11])) == 0) then {
						deleteVehicle _x;
					};
				} forEach _nobs;
			};
#ifdef __TT__
			_nobs = nearestObjects  [GVAR(le_player_boxbose), ["GroundWeaponHolder"], 10];
			if (count _nobs > 0) then {
				{
					if (({isPlayer _x} count ((getPosATL _x) nearEntities ["CAManBase", 11])) == 0) then {
						deleteVehicle _x;
					};
				} forEach _nobs;
			};
#endif
			sleep 2.45;
		};
	};
};

for "_i" from 1 to 5 do {
	_av = missionNamespace getVariable format ["d_arty1_%1", _i];
	if !(isNil "_av") then {
		_av addEventHandler ["handleDamage", {_this call FUNC(pshootatarti);0}];	
		if (!isNull (driver _av)) then {
			(driver _av) disableAI "MOVE";
		};
		{_x addEventHandler ["handleDamage", {0}]; _x disableAI "AUTOTARGET";} forEach (crew _av);
		_av lock true;
	};
	
	_av = missionNamespace getVariable format ["d_arty2_%1", _i];
	if !(isNil "_av") then {
		_av addEventHandler ["handleDamage", {_this call FUNC(pshootatarti);0}];	
		if (!isNull (driver _av)) then {
			(driver _av) disableAI "MOVE";
		};
		{_x addEventHandler ["handleDamage", {0}]; _x disableAI "AUTOTARGET";} forEach (crew _av);
		_av lock true;
	};
};

#ifdef __SERVERFPS__
0 spawn {
	while {true} do {
		sleep 5;
		diag_log [time,diag_tickTime,diag_frameno,"FPS:",diag_fps];
		diag_log ["allgroups:",count allGroups,"allunits",count allUnits,"alldead",count allDead,"alldeadmen",count allDeadMen];
		diag_log ["allMapMarkers",count allMapMarkers,"allMissionObjects",count (allMissionObjects "All")];
	};
};
#endif

// TYRGHEN - Made configurable
if (GVAR(ServerClientFPSDisplay) == 0) then {
	0 spawn {
		while {true} do {
			[QGVAR(dfps), diag_fps] call FUNC(NetCallEventToClients);
			sleep 11.0254;
		};
	};
};

__ccppfln(x_servercustomcode.sqf);
